import { message } from "antd";
import axios from "axios";

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3005/',
    timeout: 3000
})




axiosInstance.interceptors.request.use(function (config) {
    const accessToken = localStorage.getItem('token');

    if (accessToken) {
        config.headers.authorization = 'Bearer ' + accessToken;
    }
    return config;
})

axiosInstance.interceptors.response.use(
    (response) => {
        const newToken = response.headers['token'];
        if (newToken) {
            localStorage.setItem('token', newToken);
        }
        return response;
    }, async (error) => {
        if (!error.response) {
            return Promise.reject(error);
        }
        const { data } = error.response;
        if (data.statusCode === 401) {
            message.error(data.message);

            setTimeout(() => {
                window.location.href = '/login';
            }, 1500);
        } else {
            return Promise.reject(error);
        }
    }
)





/**------------------------------登录与注册------------------------------------------------- */
export async function login(username: string, password: string) {
    return await axiosInstance.post('/user/login', {
        username, password
    })
}

//注册的验证码
export async function registerCaptcha(email: string) {
    return await axiosInstance.get('/user/register-captcha', {
        params: {
            address: email
        }
    })
}


//注册
export async function register(registerUser: RegisterUser) {
    return await axiosInstance.post('/user/register', registerUser);
}

/**--------------------------------------------------------------------------------------- */

//修改密码,通过邮箱接收验证码
export async function updatePassowrdCaptcha(email: string) {
    return await axiosInstance.get('/user/update_password/captcha', {
        params: {
            address: email
        }
    });
}

//更新密码
export async function updatePassword(data: UpdatePasswordForm) {
    return await axiosInstance.post('/user/update_password', data);
}


/*---------------------------------------用户信息-------------------------------------------*/

//获取用户信息
export async function getUserInfo() {
    return await axiosInstance.get('/user/info');
}

//更新用户信息
export async function updateInfo(data: UserInfo) {
    return await axiosInstance.post('/user/update', data);
}


//更新用户信息的验证码
export async function updateUserInfoCaptcha(email: string) {
    return await axiosInstance.get('/user/update/captcha', {
        params: {
            address: email,
        }
    });
}
/*------------------------------获取好友,群聊列表---------------------------------------- */

export async function friendshipList(name?: string) {
    return axiosInstance.get(`/friendship/list?name=${name || ''}`);
}

//厉害辣，少打一个d又找了半个小时bug

export async function groupList(name?: string) {
    return axiosInstance.get(`/group/list?name=${name || ''}`)
}


export async function chatroomList(name?:string) {
    return axiosInstance.get(`/chatroom/list?name=${name || ''}`)
}


//添加好友
export async function friendAdd(data:AddFriend){
    return axiosInstance.post('/friendship/add',data)
}

//好友申请
export async function friendRequestList() {
    return axiosInstance.get('/friendship/request_list');
}

//同意好友申请
export async function agreeFriendRequest(id:number) {
    return axiosInstance.get(`/friendship/agree/${id}`)
}

//拒绝好友申请
export async function rejectFriendRequest(id:number) {
    return axiosInstance.get(`/friendship/reject/${id}`)
}

//请求聊天记录
export async function chatHistoryList(id: number) {
    return axiosInstance.get(`/chat-history/list?chatroomId=${id}`);
}


//查找聊天室
export async function findChatroom(userId1: number, userId2: number) {
    return axiosInstance.get(`/chatroom/findChatroom`, {
        params: {
            userId1,
            userId2
        }
    });
}

//创建私聊
export async function createOneToOne(friendId: number,) {
    return axiosInstance.get(`/chatroom/create-one-to-one`, {
        params: {
            friendId,
        }
    });
}


export async function groupMembers(chatroomId: number) {
    return axiosInstance.get(`/chatroom/members`, {
        params: {
            chatroomId
        }
    });
}


//添加成员进群聊
export async function addMember(chatroomId:number,joinUsername:string){
    return axiosInstance.get(`/chatroom/join/${chatroomId}`,{
        params:{
            joinUsername
        }
    })
}


//创建群聊
export async function createGroup(name: string) {
    return axiosInstance.get(`/chatroom/create-group`, {
        params: {
            name
        }
    });
}


//收藏相关
export async function queryFavoriteList() {
    return axiosInstance.get(`/favorite/list`);
}

export async function favoriteAdd(chatHistoryId: number) {
    return axiosInstance.get(`/favorite/add`, {
        params: {
            chatHistoryId
        }
    });
}

export async function favoriteDel(id: number) {
    return axiosInstance.get(`/favorite/del`, {
        params: {
            id
        }
    });
}
/*-------------------------------获取minio资源-------------------------- */

export async function presignedUrl(fileName: string) {
    return axiosInstance.get(`/minio/presignedUrl?name=${fileName}`);
}

/**
 * 8.14
 * axios报错，因为presignedUrl?name= 少写一个等号
 * 改完又报错，因为minio少写一个i....写成mimo了
 */